package so.sao.shop.supplier.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import so.sao.shop.supplier.config.CommConstant;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.config.azure.AzureBlobService;
import so.sao.shop.supplier.config.azure.BlobUpload;
import so.sao.shop.supplier.dao.CheckingAccountRecordDao;
import so.sao.shop.supplier.dao.UserDao;
import so.sao.shop.supplier.domain.CheckingAccountRecord;
import so.sao.shop.supplier.domain.User;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.service.CheckingAccountRecordService;
import so.sao.shop.supplier.util.ExcelReader;
import so.sao.shop.supplier.util.JwtTokenUtil;
import so.sao.shop.supplier.util.Ognl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>Version: supplier V1.2.0 </p>
 * <p>Title: CheckingAccountRecordServiceImpl</p>
 * <p>Description: 对账记录</p>
 *
 * @author: fangzhou
 * @Date: Created in 2017/11/22 10:41
 */
@Service
public class CheckingAccountRecordServiceImpl implements CheckingAccountRecordService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private CheckingAccountRecordDao checkingAccountRecordDao;
    @Autowired
    private AzureBlobService azureBlobService;
    @Override
    public Result uploadAccountCheckingExcel(MultipartFile excelFile, String tempPath,User user) {
        String  filename = excelFile.getOriginalFilename();
        //上传成功封装为result返回页面
        List<BlobUpload> blobUploadList =azureBlobService.uploadFiles(new MultipartFile[] {excelFile}, CommConstant.AZURE_CONTAINER.toLowerCase());
        if(blobUploadList == null){
            return Result.fail("上传失败");
        }
        BlobUpload blobUpload = blobUploadList.get(0);
        blobUpload.setOriginalFileName(filename);
       //根据用户id和对账状态查询相应的对账记录
        List<CheckingAccountRecord> checkingAccountRecordList=checkingAccountRecordDao.findByCheckerId(user.getId());
        for ( CheckingAccountRecord  checkingAccountRecord:checkingAccountRecordList){
            //修改上次上传的对账记录状态为已失效
            checkingAccountRecordDao.updateIsCheckingById(checkingAccountRecord.getId());
        }
       //封装对账记录对象
        CheckingAccountRecord checkingAccountRecord=new CheckingAccountRecord();
        checkingAccountRecord.setCheckerId(user.getId());
        checkingAccountRecord.setCheckerName(user.getUsername());
        checkingAccountRecord.setExcelUrl(blobUpload.getFileUrl());
        checkingAccountRecord.setIsChecking(0);
        checkingAccountRecord.setCreatedAt(new Date());
        checkingAccountRecord.setUpdatedAt(new Date());
        //保存对账记录
       checkingAccountRecordDao.save(checkingAccountRecord);
        return Result.success("上传成功!");
    }
}
